<?php

/**
 * 公共类库
 */
class CommonUtils
{
    /**
     * 返回请求参数的值
     */
    public static function input($name = '', $defaultValue = '', $method = 'param')
    {
        $data = [];
        switch ($method) {
            case 'GET':
                $data = $_GET;
                break;
            default:
                $content = file_get_contents('php://input');
                if ($content) {
                    $httpAccept = $_SERVER['HTTP_ACCEPT'];
                    if (false !== strpos($httpAccept, 'json')) {
                        // Ajax 方式 Post 提交，按照 {key1:val1,key2:val2} 的方式进行编码
                        $data = (array) json_decode($content, true);
                    } else if (false !== strpos($httpAccept, 'x-www-form-urlencoded')) {
                        // 浏览器原生 Post 提交，按照 key1=val1&key2=val2 的方式进行编码
                        parse_str($content, $data);
                    }
                }
                $data = array_merge($data, $_POST);
                break;
        }
        if ($method == 'param') {
            $data = array_merge($data, $_GET);
        }
        if (!$name) {
            return $data;
        }
        if (isset($data[$name])) {
            return $data[$name];
        }
        return $defaultValue;
    }
    /**
     * 校验参数
     */
    public static function validate($rules, $data)
    {
        foreach ($rules as $k => $rules) {
            $pos = strpos($k, '|');
            if ($pos) {
                $title = substr($k, $pos + 1);
                $k = substr($k, 0, $pos);
            } else {
                $title = $k;
            }
            $rules = array_unique(array_filter(explode('|', $rules)));
            foreach ($rules as $rule) {
                $ruleAttr = '';
                $pos = strpos($rule, ':');
                if ($pos) {
                    $ruleAttr = substr($rule, $pos + 1);
                    $rule = substr($rule, 0, $pos);
                }
                switch ($rule) {
                    case 'require':
                        if (!isset($data[$k])) {
                            $errmsg = "{$title}是必填项目";
                            return self::stdMessage(false, $errmsg);
                        }
                        break;
                        case 'notblank':
                            if (!isset($data[$k]) || !strlen(trim($data[$k]))) {
                                $errmsg = "{$title}不能为空";
                                return self::stdMessage(false, $errmsg);
                            }
                            break;
                    case 'min': // min:1
                        if (!isset($data[$k])) {
                            break;
                        }
                        if (!$ruleAttr) {
                            $ruleAttr = 1;
                        }
                        if (strlen($data[$k]) < $ruleAttr) {
                            $errmsg = "{$title}最少{$ruleAttr}个字符";
                            return self::stdMessage(false, $errmsg);
                        }
                        break;
                }
            }
        }
        return self::stdMessage(true, '校验成功');
    }
    /**
     * 格式化标准返回消息
     */
    public static function stdMessage($status, $message, $data = null, $code = 200)
    {
        return ['status' => $status, 'message' => $message, 'data' => $data, 'code' => $code];
    }
    public static function responseJsonMessage($status, $message, $data = null, $code = 200)
    {
        self::outputJson(self::stdMessage($status, $message, $data, $code));
    }
    /**
     * 输出JSON内容
     */
    public static function outputJson($data)
    {
        header('Content-type:application/json; charset=utf-8');
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        exit;
    }
    /**
     * 字节单位转换
     */
    public static function formatBytes($size, $digits = 2)
    {
        if (!$size) {
            return $size;
        }
        $base = 1024;
        $unit = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
        // return round($size / pow($base, ($i = floor(log($size, $base)))), 2) . ' ' . $unit[$i];
        $i = floor(log($size, $base));
        $n = count($unit);
        if ($i >= $n) {
            $i = $n - 1;
        }
        return round($size / pow($base, $i), $digits) . ' ' . $unit[$i];
    }

    /**
     * 返回服务器 IP
     * 参考：SERVER_NAME 和 HTTP_HOST 的区别 (http://blog.sina.com.cn/s/blog_6d96d3160100q39x.html)
     * @version 1.0 2017-10-13 Added.
     */
    public static function getHostIP()
    {
        //return $_SERVER['HTTP_HOST']; // 有服务器域名则优先返回域名，否则返回服务器 ip
        return gethostbyname($_SERVER['SERVER_NAME']); // 返回服务器IP
    }
}
